package com.sinopec.basemodule.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.AppCompatTextView;

import com.gyf.immersionbar.ImmersionBar;
import com.sinopec.basemodule.R;
import com.sinopec.basemodule.common.Logger;
import com.sinopec.basemodule.constants.DialogConst;
import com.sinopec.basemodule.dialog.TankerDialog;
import com.sinopec.basemodule.dialog.TankerProgressDialog;
import com.sinopec.basemodule.utils.DensityUtils;
import com.sinopec.basemodule.utils.NetUtil;
import com.sinopec.basemodule.utils.ShowMassageUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.PublishSubject;

/**
 * Created by ronny on 2017/8/16.
 */

public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity
        implements BaseView {
    //对svg是两处显示进行适配
    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    public T mPresenter;
    protected TankerProgressDialog progressDialog;
    protected BaseActivity mContext;
    protected TankerDialog dialog;
    public final PublishSubject<ActivityLifeCycleEvent> lifecycleSubject = PublishSubject.create();
    protected InputMethodManager imm;
    protected static final int RESULT_CAMERA_IMAGE = 1, RESULT_LOAD_IMAGE = 2;
    protected ImageView leftAction;
    protected TextView tvTitle;
    protected AppCompatTextView rightAction;
    protected RelativeLayout toolbar;
    protected RelativeLayout viewContainer;
    protected CustomToolbar mCustomToolbar;
    private boolean tokenDialogIsShowed = false;
    protected ImageView rightIcon;
    public RelativeLayout rootView;
    protected View statusLine;
    protected ImageView errorImg;
    private TextView tvMessageNum;
    private ArrayList<Disposable> disposables = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        Logger.e("123===", "当前activity=" + this.getLocalClassName());

        if (!isTaskRoot()
                && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
                && getIntent().getAction() != null
                && getIntent().getAction().equals(Intent.ACTION_MAIN)) {

            finish();
            return;
        }

        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        lifecycleSubject.onNext(ActivityLifeCycleEvent.CREATE);
        setContentView(R.layout.activity_base);
        //Activity的管理类
        AppManager.getInstance().addActivity(this); //添加到栈中
        viewContainer = findViewById(R.id.view_container);
        rootView = findViewById(R.id.root_view);
        setCustomContentView(getContentView());
        leftAction = findViewById(R.id.left_action);
        tvTitle = findViewById(R.id.tv_title);
        rightAction = findViewById(R.id.right_action);
        rightIcon = findViewById(R.id.right_icon);
        toolbar = findViewById(R.id.toolbar);
        statusLine = findViewById(R.id.status_line);
        errorImg = findViewById(R.id.iv_error_data);
        tvMessageNum = findViewById(R.id.tv_message_num);
        mContext = this;
        setStatusBar();
       /* StatusBarUtil.StatusBarLightMode(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags =
                    (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }*/
//    Logger.setTag(TAG);
        initDialog();
        initToolbar();

        initView(savedInstanceState);
        initData();
        initEvent();
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    }

    /**
     * 设置状态栏
     */
    protected void setStatusBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }


    protected abstract void initView(Bundle savedInstanceState);

    protected void initData() {
    }

    @SuppressLint("ClickableViewAccessibility")
    protected void initEvent() {
        //点击空白处隐藏键盘
        rootView.setOnTouchListener((v, motionEvent) -> {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                if (manager != null && getCurrentFocus() != null
                        && getCurrentFocus().getWindowToken() != null) {
                    if (isSoftShowing()) {
                        hideSoftKeyboard();
                    }
//                    manager.hideSoftInputFromWindow(getCurrentFocus()
//                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
            return false;
        });
        leftAction.setOnClickListener(view -> {
            if (mCustomToolbar != null && mCustomToolbar.getOnLeftClickListener() != null) {
                mCustomToolbar.getOnLeftClickListener().onClick(view);
            } else {
                finish();
            }
        });
        rightAction.setOnClickListener(view -> {
            if (mCustomToolbar != null && mCustomToolbar.getOnRightClickListener() != null) {
                mCustomToolbar.getOnRightClickListener().onClick(view);
            }
        });
        rightIcon.setOnClickListener(view -> {
            if (mCustomToolbar != null && mCustomToolbar.getOnRightIconClickListener() != null) {
                mCustomToolbar.getOnRightIconClickListener().onClick(view);
            }
        });
    }

    protected void initToolbar() {
        mCustomToolbar = CustomToolbar.newInstance(toolbar, leftAction, rightAction, rightIcon, tvTitle, statusLine, tvMessageNum);
        configToolbar(mCustomToolbar);
    }

    @Override
    public void setCustomContentView(@LayoutRes int layoutResID) {
        LayoutInflater.from(this).inflate(layoutResID, viewContainer);
    }

    @Override
    public void showProgress() {
        showProgress(false);
    }

    @Override
    public void showProgress(boolean cancelable) {
        if (!progressDialog.isShowing()) {
            progressDialog.setText("加载中···");
            progressDialog.setCanceledOnTouchOutside(cancelable);
            progressDialog.show();
        }
    }

    @Override
    public void showProgress(String msg) {
        if (!progressDialog.isShowing()) {
            progressDialog.setText(msg);
            progressDialog.show();
        }
    }

    @Override
    public void dismissProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void showProgress(String msg, int ImageRes) {
        if (!progressDialog.isShowing()) {
            progressDialog.setText(msg);
            progressDialog.setImage(ImageRes);
            progressDialog.show();
        }
    }

    protected void initDialog() {
        dialog = new TankerDialog(this);
        progressDialog = new TankerProgressDialog(mContext, R.style.CustomDialog);
        progressDialog.setCanceledOnTouchOutside(false);
//        progressDialog.setText("加载中···");
    }


    @Override
    public BaseActivity getContext() {
        return mContext;
    }

    /**
     * 只有提示语的弹窗
     *
     * @param msg
     */
    @Override
    public void showAlertDialog(String msg, TankerDialog.OptionListener optionListener) {
        showAlertDialog(msg, -1, optionListener);
    }

//    /**
//     * 只有提示语的弹窗
//     */
//
//    public void showEditDialog(String title, String hint, String transportTonnage, TankerDialog.OptionListener optionListener) {
//        Bundle bundle = new Bundle();
//        if (!TextUtils.isEmpty(title)) {
//            bundle.putString(DialogConst.DIALOG_TITLE_TEXT, title);
//        }
//        bundle.putString(DialogConst.DIALOG_CONTENT_TEXT, transportTonnage);
//        bundle.putInt(DialogConst.DIALOG_MESSAGE_TYPE, TankerDialog.EDIT_DIALOG);
//        bundle.putBoolean(DialogConst.DIALOG_NOT_CANCEL_DIALOG_AFTER_CLICK, true);
//        bundle.putString(DialogConst.DIALOG_CONTENT_HINT, hint);
//        showDialog(bundle, optionListener);
//    }


    public void showAlertDialog(String title, String msg, int ImageRes, TankerDialog.OptionListener optionListener) {
        Bundle bundle = new Bundle();
        if (!TextUtils.isEmpty(title)) {
            bundle.putString(DialogConst.DIALOG_TITLE_TEXT, title);
        }
        bundle.putInt(DialogConst.DIALOG_MESSAGE_TYPE, TankerDialog.IMAGE_DIALOG_WITH_TWO_CONTENT);
        bundle.putInt(DialogConst.DIALOG_HEIGHT, ImageRes == -1 ? DialogConst.DIALOG_DEFAULT_HEIGHT : DialogConst.DIALOG_SECOND_HEIGHT);
        bundle.putString(DialogConst.DIALOG_CONTENT_TEXT, msg);
        if (ImageRes != -1) {
            bundle.putInt(DialogConst.DIALOG_IMAGE_RES_ID, ImageRes);
        }
        showDialog(bundle, optionListener);

    }

    public void showDialog(Bundle bundle, TankerDialog.OptionListener optionListener) {
        dialog.switchStyleAndShow(bundle, optionListener);
    }

//    /**
//     * 默认title 工作时间：早9:00-晚8:00
//     *
//     * @param msg
//     * @param optionListener
//     */
//    public void showPhoneDialog(String msg, TankerDialog.OptionListener optionListener) {
//        Bundle bundle = new Bundle();
//        bundle.putInt(DialogConst.DIALOG_MESSAGE_TYPE, TankerDialog.PHONE_DIALOG);
//        bundle.putString(DialogConst.DIALOG_CONTENT_TEXT, msg);
//        showDialog(bundle, optionListener);
//    }

//    /**
//     * @Description: 打电话弹出框可以传递title的方法
//     * @date 2018/5/1
//     * @author lwj
//     */
//    public void showPhoneDialog(String msg, String title, TankerDialog.OptionListener optionListener) {
//        Bundle bundle = new Bundle();
//        bundle.putInt(DialogConst.DIALOG_MESSAGE_TYPE, TankerDialog.PHONE_DIALOG);
//        bundle.putString(DialogConst.DIALOG_CONTENT_TEXT, msg);
//        if (!TextUtils.isEmpty(title)) {
//            bundle.putString(DialogConst.DIALOG_TITLE_TEXT, title);
//        }
//        showDialog(bundle, optionListener);
//    }


    @Override
    public void showAlertDialog(String msg, int ImageRes, TankerDialog.OptionListener optionListener) {
        showAlertDialog(null, msg, ImageRes, optionListener);
    }

    @Override
    public void showAlertDialogNoCancel(String content, String secondContent, int ImageRes, TankerDialog.OptionListener optionListener) {
        Bundle bundle = new Bundle();
        bundle.putInt(DialogConst.DIALOG_MESSAGE_TYPE, TankerDialog.IMAGE_DIALOG);
        bundle.putString(DialogConst.DIALOG_CONTENT_TEXT, content);
        bundle.putInt(DialogConst.DIALOG_HEIGHT, DialogConst.DIALOG_SECOND_HEIGHT);
        bundle.putString(DialogConst.DIALOG_SECOND_CONTENT_TEXT, secondContent);
        bundle.putBoolean(DialogConst.DIALOG_SHOW_CANCEL, false);
        if (ImageRes != -1) {
            bundle.putInt(DialogConst.DIALOG_IMAGE_RES_ID, ImageRes);
        }
        dialog.switchStyleAndShow(bundle, optionListener);
    }

    @Override
    public void showAlertDialogNoCancel(String content, String confirmText, TankerDialog.OptionListener optionListener) {
        Bundle bundle = new Bundle();
        bundle.putInt(DialogConst.DIALOG_MESSAGE_TYPE, TankerDialog.IMAGE_DIALOG_WITHOUT_IMG);
        bundle.putString(DialogConst.DIALOG_CONTENT_TEXT, content);
        bundle.putString(DialogConst.DIALOG_CONFIRM_TEXT, confirmText);
        bundle.putBoolean(DialogConst.DIALOG_SHOW_CANCEL, false);
        dialog.switchStyleAndShow(bundle, optionListener);
    }


    @Override
    public void showMessage(String error) {
        ShowMassageUtil.showErrorToast(error);
    }

    @Override
    public void showErrorMessage(int code, String msg) {
        ShowMassageUtil.showErrorToast(code + "", msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            dialog = null;
        }
        if (progressDialog != null) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            progressDialog = null;
        }
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        for (Disposable disposable : disposables) {
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
        fixInputMethodManagerLeak(this);
        //Activity的管理类
        AppManager.getInstance().finishActivity(this); //从栈中移除
    }

    @Override
    public void navigationTo(Class cls) {
        Intent intent = new Intent(this, cls);
        navigationTo(intent);
    }

    @Override
    public void navigationTo(Intent intent) {
        if (NetUtil.isNetworkAvailable(this)) {
            startActivity(intent);
        } else {
            showMessage(getString(R.string.error_net));
        }
    }

//    private String getRunningActivityName() {
//        String contextString = getLocalClassName();
//        return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.length());
//    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                           int[] grantResults) {
//        if (requestCode == 1 && permissions.length > 0) {
//            if (permissions[0].equals(Manifest.permission.CALL_PHONE)
//                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
////                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + AppConstants.getServicePhone()));
////                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
////                        != PackageManager.PERMISSION_GRANTED) {
////                    return;
////                } else {
////                    startActivity(intent);
////                }
//            } else {//没有获得到权限
//                showMessage("您已禁止该权限，需要重新开启。");
//            }
//        }
//    }

    @Override
    protected void onPause() {
        lifecycleSubject.onNext(ActivityLifeCycleEvent.PAUSE);
        super.onPause();
    }

    @Override
    protected void onStop() {
        lifecycleSubject.onNext(ActivityLifeCycleEvent.STOP);
        super.onStop();
    }

    @Override
    public PublishSubject<ActivityLifeCycleEvent> getLifecycleSubject() {
        return lifecycleSubject;
    }

    @Override
    public Drawable getmDrawable(@DrawableRes int drawableRes) {
        return getResources().getDrawable(drawableRes);
    }

    @Override
    public int getmColor(int resColor) {
        return getResources().getColor(resColor);
    }

    public void hideSoftKeyboard() {
        boolean isOpen = isSoftShowing();
        if (isOpen) {//打开则执行下面方法进行关闭
            // 隐藏软键盘
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //底部又一个button 60dp高
        return screenHeight - rect.bottom > DensityUtils.dip2px(70);
    }

    protected void addDisposable(Disposable disposable) {
        if (disposable == null) {
            return;
        }
        disposables.add(disposable);
    }

    public ArrayList<Disposable> getDisposables() {
        return disposables;
    }

    public static void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
        Field f = null;
        Object obj_get = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                }
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
}
